<template>
  <div class="upload-component-box">
    <el-dialog
      top="10vh"
      width="80%"
      :title="title"
      :show-close="true"
      :append-to-body="false"
      :visible.sync="dialog_visible"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @closed="closeDialog"
    >
      <div class="main">
        <div class="upload">
          <el-upload
            ref="upload"
            class="upload-widget"
            drag
            with-credentials
            :accept="data_upload.upload_accept"
            :multiple="false"
            :show-file-list="false"
            action="no_use_string"
            :auto-upload="false"
            :on-change="uploadChange"
            :before-upload="onBeforeUpload"
            :http-request="onHttpRequest"
          >
            <template v-if="data_upload.file_list.length === 0">
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
              </div>
            </template>
            <template v-else>
              <i class="el-icon-document-add" />
              <div class="el-upload__text">
                {{ data_upload.fileName }}
              </div>
            </template>
            <div slot="tip" class="el-upload__tip">
              模板导入文件支持 .xls 或 .xlsx 文件
            </div>
          </el-upload>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">
          取 消
        </el-button>
        <el-button
          :disabled="data_upload.file_list.length === 0"
          type="primary"
          @click="confirmDialog"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      top="30vh"
      width="600px"
      :show-close="false"
      :lock-scroll="true"
      :visible.sync="progress_visible"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @closed="closeProgressDialog"
    >
      <div class="main">
        <div class="progress">
          <b class="percentage">{{ progress_val }}%</b>
          <el-progress
            :show-text="false"
            :text-inside="true"
            :stroke-width="26"
            :percentage="progress_val"
          />
          <span class="tip">产品数据导入中</span>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      top="30vh"
      width="800px"
      :show-close="false"
      :lock-scroll="true"
      :visible.sync="complete_visible"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @closed="closeCompleteDialog"
    >
      <div class="main">
        <i class="el-icon-close" @click="closeCompleteDialog" />
        <el-row class="row">
          <el-col :xs="3" :sm="3">
            <i class="icon el-icon-circle-check" />
          </el-col>
          <el-col :xs="21" :sm="21">
            <div class="item">
              导入成功数量
              <b>{{ payload_data.successCount }}条</b>
            </div>
          </el-col>
        </el-row>
        <el-row v-if="payload_data.failureCount > 0" class="row">
          <el-col :xs="3" :sm="3">
            <i class="icon el-icon-warning-outline" />
          </el-col>
          <el-col :xs="5" :sm="5">
            <div class="item">
              导入失败数量
              <b>{{ payload_data.failureCount }}条</b>
            </div>
          </el-col>
          <el-col v-if="payload_data.failureCount > 0" :xs="16" :sm="16">
            <div class="item">
              <b>
                <el-button type="text" @click="downLoadFailtureFile"
                  >未成功导入数据下载</el-button
                >
              </b>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { ApiMMallWeb } from '@services/api';
// import { downloadFailUploadDataTH, uploadReturnedProduct } from '@api/m_mall_web_v1';
import { $loadFileSimply } from '@const/loadFileOps';
import { fileDownload } from '@const/utils.js';

export default {
  name: 'UploadExcelDialogComponent',
  inject: ['downloadFailUploadData', 'uploadProduct'],
  props: {
    title: {
      type: String,
      default: '模板导入'
    },
    params: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      data_upload: {
        // 这个的作用实际上是显隐的切换
        file_list: [],
        fileName: '',
        upload_accept: '.xls,.xlsx'
      },
      payload_data: {
        successCount: 0,
        failureCount: 0
      },
      dialog_visible: false,
      progress_visible: false,
      complete_visible: false,
      progress_val: 0,
      fileTemplateId: '' // 用于失败文件下载
    };
  },
  computed: {
    apiMMallWeb() {
      return new ApiMMallWeb(this.fetcher);
    }
  },
  watch: {
    progress_val: {
      handler(nv) {
        if (nv === 100) {
          this.closeProgressDialog();
          this.complete_visible = true;
        }
      }
    }
  },
  methods: {
    downLoadFailtureFile() {
      $loadFileSimply({
        url: this.downloadFailUploadData,
        method: 'post',
        params: { templateId: this.fileTemplateId }
      })
        .then(res => {
          fileDownload(res, '退货产品导入失败.xlsx');
        })
        .catch(() => {
          this.$message.error('下载文件失败!');
        });
    },
    closeProgressDialog() {
      this.progress_visible = false;
      this.progress_val = 0;
    },
    closeCompleteDialog() {
      this.complete_visible = false;
    },
    closeDialog() {
      this.dialog_visible = false;
      this.$refs.upload.clearFiles();
      this.data_upload.file_list = [];
      this.fileName = [];
    },
    confirmDialog() {
      this.$refs.upload.submit();
      this.closeDialog();
    },
    // 上传进度回调
    onUploadProgress(progressEvent) {
      if (progressEvent.lengthComputable) {
        let val = (progressEvent.loaded / progressEvent.total) * 100;
        val = parseInt(val, 10);
        // 这里的进度只能表明文件已经上传到后台，但是后台有没有处理完还不知道
        // 因此不能直接显示为100%，不然用户会误以为已经上传完毕，关掉浏览器的话就可能导致上传失败
        // 等响应回来时，再将进度设为100%
        if (val === 100) val = 90;
        this.progress_val = val;
      }
    },
    onBeforeUpload(file) {
      const FileExt = file.name.replace(/.+\./, ''); // 名字后缀
      const isLt10M = file.size / 1024 / 1024 < 10; // 文件大小
      const format = this.data_upload.upload_accept.includes(
        FileExt.toLowerCase()
      );
      if (!format) {
        this.$message.error(
          `上传文件只支持${this.data_upload.upload_accept}类型!`
        );
      } else if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!');
      }
      return isLt10M && format;
    },
    onHttpRequest(data) {
      this.progress_visible = true;
      const fd = new FormData();
      fd.append('file', data.file);
      console.log(this.params, 'params--------------');
      fd.append(
        'busModel',
        this.params.contract_data.busModel ||
          this.params.contract_data.businessModelCode
      );
      fd.append('productLineCode', this.params.contract_data.productLineCode);
      fd.append(
        'vendorNum',
        this.params.supplier_data.supplierCode ||
          this.params.supplier_data.vendorCode
      );
      fd.append('orderCodeRelate', this.params.orderCodeRelate || '');
      this.$axios({
        method: 'post',
        url: this.uploadProduct,
        headers: { 'Content-Type': 'multipart/form-data' },
        onUploadProgress: this.onUploadProgress,
        data: fd
      })
        .then(res => {
          const { code, payload } = res.data;
          if (!Number(code)) {
            if (typeof payload !== 'string') {
              this.payload_data = payload;
              this.fileTemplateId = this.payload_data.templateId;
              this.progress_val = 100;
              let { orderProductVOList } = payload;
              orderProductVOList = orderProductVOList.map(item => ({
                mixsIds:
                  item.orginalOrderCode +
                  item.seqNo +
                  item.productCode +
                  item.batchNo +
                  item.validDate +
                  item.referencePrice,
                ...item,
                productCount: item.productCount || 1
              }));
              this.$emit('complete', this.resturcPayload(orderProductVOList));
            } else {
              this.$message.error(payload);
              this.closeProgressDialog();
            }
          } else {
            this.$message.error('数据解析失败');
          }
        })
        .catch(() => {})
        .finally(() => {});
    },
    resturcPayload(payload) {
      const data = payload;
      data.forEach(item => {
        const newItem = item;
        newItem.referencePrice = item.productPrice || ''; // 产品价格
        newItem.productUnitName = item.productUnit; // 单位
        newItem.attribute1 = item.specs; // 规格（与型号一致）
        newItem.attribute5 = item.barCode; // 条形码
      });
      return data;
    },
    uploadChange(file, fileList) {
      // 通过这种代码来保证每次上传只有一个文件
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
      this.data_upload.fileName = fileList[0].name;
      this.data_upload.file_list = fileList;
    }
  }
};
</script>
<style lang="less" scoped>
.upload-component-box {
  .upload {
    width: 360px;
    margin: 0 auto;

    .upload-widget {
      .el-icon-document-add {
        font-size: 67px;
        color: #a7b1c7;
        margin: 40px 0 16px;
        line-height: 50px;
      }

      .el-upload__text {
        padding: 0 20px;
      }

      .el-upload__tip {
        color: #999;
        text-align: center;
      }
    }
  }

  /deep/ .el-dialog__header {
    display: none;
  }

  .progress {
    width: 100%;
    padding: 20px 0;
    margin: 0 auto;

    .percentage {
      color: #00f;
      line-height: 32px;
      font-size: 18px;
      text-align: center;
      display: block;
      margin-bottom: 20px;
    }

    .tip {
      color: #333;
      font-size: 16px;
      text-align: center;
      margin-top: 20px;
      display: block;
    }
  }
  /deep/ .el-dialog__header {
    display: none;
  }

  .row {
    line-height: 24px;
    border: solid 1px #ddd;
    padding: 15px 0;
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0 !important;
    }

    b {
      color: #1890ff;
      font-weight: bold;
      display: block;
    }

    .icon {
      line-height: 48px;
      text-align: center;
      font-size: 48px;
      display: block;
    }

    .el-icon-circle-check {
      color: #0d0;
    }

    .el-icon-warning-outline {
      color: #f90;
    }
  }

  .el-icon-close {
    width: 16px;
    color: #909399;
    cursor: pointer;
    line-height: 16px;
    font-size: 16px;
    text-align: center;
    position: absolute;
    top: 4px;
    right: 4px;

    &:hover {
      color: #000;
    }
  }
}

.dialog-footer {
  text-align: center;
}
</style>
